<?php

namespace App\Http\Controllers\admin;

use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\common\PublicController;
use App\Http\Controllers\common\LoraController;
//模型
use App\Models\Building;
use App\Models\Room;
use App\Models\Gateway;
use App\Models\Models;

class GatewayController extends PublicController
{
    private $type_id = '7';
    static $allGateway = [];
    //设备列表
    public function getIndex(Request $request)
    {
        $page = $request->input('page',1);
        /*搜索条件始*/
        //搜索条件
        $get['area'] = $request -> input('area','');
        if($get['area']){
            $this -> where .= ' -> where("area.name","like","%".$get["area"]."%")';
        }
        $get['building'] = $request -> input('building','');
        if($get['building']){
            $this -> where .= ' -> where("building.name","like","%".$get["building"]."%")';
        }
        $get['room'] = $request -> input('room','');
        if($get['room']){
            $this -> where .= ' -> where("room.name","like","%".$get["room"]."%")';
        }
        $get['gw'] = $request -> input('gw','');
        if($get['gw']){
            $this -> where .= ' -> where("GatewayID","like","%".$get["gw"]."%")';
        }
        $get['model'] = $request -> input('model','');
        if($get['model']){
            $this -> where .= ' -> where("model.name","like","%".$get["model"]."%")';
        }
        $get['gwn'] = $request -> input('gwn','');
        if($get['gwn']){
            $this -> where .= ' -> where("gateway.name","like","%".$get["gwn"]."%")';
        }
        /*搜索条件末*/
        /*代理商搜索始*/
        //获取自身及旗下所有代理商
        $agentInfo = $this -> agentInfo($request -> cookie('logon')['agent_id']);
        /*代理商搜索末*/
        $pageInfo = '';
        if($this -> area_ids === '0'){
            eval('$pageInfo = DB::table("gateway")
            -> leftJoin("room","gateway.room_id","=","room.id")
            -> leftJoin("building","room.building_id","=","building.id")
            -> leftJoin("area","building.area_id","=","area.id")
            -> leftJoin("model","gateway.model_id","=","model.id")
            -> where("gateway.agent_id",$this -> agent_id)
            '.$this -> where.' 
            -> paginate(10);');
        }else{
            eval('$pageInfo = DB::table("gateway")
            -> leftJoin("room","gateway.room_id","=","room.id")
            -> leftJoin("building","room.building_id","=","building.id")
            -> leftJoin("area","building.area_id","=","area.id")
            -> leftJoin("model","gateway.model_id","=","model.id")
            -> where("gateway.agent_id",$this -> agent_id)
            '.$this -> where.'
            -> whereIn("area.id",explode(",",$this -> area_ids))
            -> paginate(10);');
        }
        //给页面分配数据
        if(empty(self::$allGateway)){
            $data = '';
            if($this -> area_ids === '0'){
                eval('$data = DB::table("gateway")
                -> leftJoin("room","gateway.room_id","=","room.id")
                -> leftJoin("building","room.building_id","=","building.id")
                -> leftJoin("area","building.area_id","=","area.id")
                -> leftJoin("model","gateway.model_id","=","model.id")
                -> where("gateway.agent_id",$this -> agent_id)
                -> select("gateway.*","room.name as room_name","room.building_id","building.name as building_name","building.area_id","area.name as area_name","model.name as model_name")
                '.$this->where.'
                -> get();');
            }else{
                eval('$data = DB::table("gateway")
                -> leftJoin("room","gateway.room_id","=","room.id")
                -> leftJoin("building","room.building_id","=","building.id")
                -> leftJoin("area","building.area_id","=","area.id")
                -> leftJoin("model","gateway.model_id","=","model.id")
                -> where("gateway.agent_id",$this -> agent_id)
                -> select("gateway.*","room.name as room_name","room.building_id","building.name as building_name","building.area_id","area.name as area_name","model.name as model_name")
                '.$this->where.'
                -> whereIn("area.id",explode(",",$this -> area_ids))
                -> get();');
            }
            foreach ($data as $key=>$val){
                $areaMember = '';
                $buildingMember = '';
                $roomMember = '';
                $areaMemberArr = $this -> memberInRange('area',$data[$key]['area_id']);
                $buildingMemberArr = $this -> memberInRange('building',$data[$key]['building_id']);
                $roomMemberArr = $this -> memberInRange('room',$val['room_id']);
                if(!empty($areaMemberArr)){
                    foreach($areaMemberArr as $v){
                        $areaMember .= $v['name'].',';
                    }
                }
                if(!empty($areaMemberArr)) {
                    foreach ($buildingMemberArr as $v) {
                        $buildingMember .= $v['name'] . ',';
                    }
                }
                if(!empty($roomMemberArr)) {
                    foreach ($roomMemberArr as $v) {
                        $roomMember .= $v['name'] . ',';
                    }
                }
                $data[$key]['member'] = array(
                    'area'=>substr($areaMember,0,-1),
                    'building'=>substr($buildingMember,0,-1),
                    'room'=>substr($roomMember,0,-1)
                );
            }
            self::$allGateway = $data;
        }
        //dd(self::$allGateway);
        $online = [];
        $offline = [];
        $others = [];
        foreach (self::$allGateway as $k=>$v){
            $status = $this -> getGatewayStatus($v['GatewayID']);
            if($status){
                $v['gws'] = $status['state'];
                if($status['state'] == 1){
                    $online[] = $v;
                }else{
                    $offline[] = $v;
                }
            }else{
                $v['gws'] = false;
                $others[] = $v;
            }
        }
        $all = array_merge($online,$offline,$others);
        $start = ($page-1)*10;
        $data = array_slice($all,$start,10);
        $get['agent_id'] = $this -> agent_id;
        return view('admin.gateway.index',['data'=>$data,'info'=>$pageInfo,'agentInfo'=>$agentInfo,'request'=>$request -> all(),'get'=>$get,'areaids' => $this->area_ids]);
    }

    //添加设备页面
    public function getCreate()
    {
        /*//获取所有的设备
        $deviceInfo = DB::table('device') -> select('DevEUI') -> get();*/
        //获取代理商下的所有区域
        if($this -> area_ids === '0'){
            $areaInfo = DB::table('area') ->where('agent_id',$this->agent_id) -> get();
        }else{
            $areaInfo = DB::table('area') ->where('agent_id',$this->agent_id) -> whereIn("area.id",explode(",",$this -> area_ids)) -> get();
        }
        //获取烟感设备的所有型号
        $modelInfo = DB::table('model') -> where('type_id',$this -> type_id) -> get();
        return view('admin.gateway.create',['areaInfo'=>$areaInfo,'modelInfo'=>$modelInfo]);
    }

    //添加处理页面
    public function postStore(Request $request)
    {
        $info = $request -> except('_token');
        $info['agent_id'] = $this -> agent_id;
        //获取网关型号
        $model_name = Models::find($info['model_id']) -> name;
        //添加到lora
        $lora = new LoraController();
        $lora -> addGateway($info['name'],$info['GatewayID'],$model_name,$info['power']);
        //添加到烟感设备表
        $resObj = Gateway::create($info);
            if($resObj){
                $data['status'] = 1;
            }else{
                $data['status'] = -1;
            }
        echo json_encode($data);
    }

    //编辑设备页面
    public function getEdit(Request $request)
    {
        $id = $request -> input('id');
        //获取烟感设备信息
        $Info = Gateway::find($id);
        //获取区域建筑id
        if($Info -> room_id&&Room::find($Info -> room_id)){
            //获取建筑id
            $Info['building_id'] = Room::find($Info -> room_id) -> building_id;
            if($Info['building_id']&&Building::find($Info['building_id'])){
                //获取区域id
                $Info['area_id'] = Building::find($Info['building_id']) -> area_id;
            }else{
                $Info['area_id'] = null;
            }
        }else{
            $Info['building_id'] = null;
            $Info['area_id'] = null;
        }
        //获取代理商下的所有区域
        if($this -> area_ids === '0'){
            $areaInfo = DB::table('area') ->where('agent_id',$this->agent_id) -> get();
        }else{
            $areaInfo = DB::table('area') ->where('agent_id',$this->agent_id) -> whereIn("area.id",explode(",",$this -> area_ids)) -> get();
        }
        //获取该房间所在区域的所有建筑
        $buildingInfo = Building::where('area_id',$Info['area_id']) -> get() -> toarray();
        //获取该房间所在建筑的所有房间
        $roomInfo = Room::where('building_id',$Info['building_id']) -> get() -> toarray();
        //获取烟感设备的所有型号
        $modelInfo = DB::table('model') -> where('type_id',$this -> type_id) -> get();
        return view('admin.gateway.edit',['data'=>$Info,'areaInfo'=>$areaInfo,'buildingInfo'=>$buildingInfo,'roomInfo'=>$roomInfo,'modelInfo'=>$modelInfo]);
    }

    //编辑处理页面
    public function postUpdate(Request $request)
    {
        $id = $request -> input('id');
        $info = $request -> except('_token','id');
        //修改smoke表
        $res = Gateway::find($id) -> update($info);
        if($res){
            $data['status'] = 1;
        }else{
            $data['status'] = -1;
        }
        echo json_encode($data);
    }

    //删除处理页面
    public function postDestroy(Request $request)
    {
        $id = $request -> input('id');
        //查询网关表
        $GatewayID = Gateway::find($id) -> GatewayID;
        //从lora删除
        $lora = new LoraController();
        $lora -> delGateway($GatewayID);
        //查询区域和客户的关系表并删除
        $res = Gateway::destroy($id);
        if($res){
            $data['status'] = 1;
        }else{
            $data['status'] = -1;
        }
        echo json_encode($data);
    }

    //通知状态处理页面
    public function postStatus(Request $request){
        $id = $request -> input('id');
        $status = $request -> input('status');
        //修改设备表
        $res = Gateway::find($id) -> update(['status'=>$status]);
        if($res){
            $data['status'] = 1;
        }else{
            $data['status'] = -1;
        }
        echo json_encode($data);
    }

    public function getGatewayStatus($gw_id){
        $lora = new LoraController();
        $res = $lora -> getGatewayMsg($gw_id);
        $res = json_decode($res,true);
        if(isset($res['data'])){
            return $res['data'] ;
        }else{
            return false;
        }
    }
}
